using DXApplications.Models;
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace DXApplications.Services
{
    public class ApiService
    {
        private readonly HttpClient _httpClient;
        private string _authToken = string.Empty;

        public ApiService()
        {
            // 构建配置读取器
            var configuration = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();

            // 从配置文件中读取API基础地址
            string baseUrl = "http://localhost:5269/api/"; // 默认值
            try
            {
                var apiSettings = configuration.GetSection("ApiSettings");
                if (apiSettings != null)
                {
                    string? configUrl = apiSettings["BaseUrl"];
                    if (!string.IsNullOrEmpty(configUrl))
                    {
                        baseUrl = configUrl;
                    }
                }
            }
            catch { /* 如果配置读取失败，使用默认值 */ }

            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(baseUrl)
            };
        }

        // 登录方法
        public async Task<LoginResult> LoginAsync(string username, string password)
        {
            try
            {
                var request = new { Username = username, Password = password };
                var response = await _httpClient.PostAsJsonAsync("auth/login", request);

                if (response.IsSuccessStatusCode)
                {
                    var loginResponse = await response.Content.ReadFromJsonAsync<LoginResponse>();
                    if (loginResponse != null && loginResponse.Success)
                    {
                        _authToken = loginResponse.Token ?? string.Empty;
                        // 设置认证头
                        _httpClient.DefaultRequestHeaders.Authorization =
                            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _authToken);

                        return new LoginResult
                        {
                            Success = true,
                            User = loginResponse.User
                        };
                    }
                    else
                    {
                        return new LoginResult
                        {
                            Success = false,
                            ErrorMessage = loginResponse?.Message ?? "登录失败"
                        };
                    }
                }
                else
                {
                    var errorMessage = await response.Content.ReadAsStringAsync();
                    return new LoginResult
                    {
                        Success = false,
                        ErrorMessage = $"HTTP错误: {response.StatusCode}. {errorMessage}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new LoginResult
                {
                    Success = false,
                    ErrorMessage = $"连接错误: {ex.Message}"
                };
            }
        }

        // 获取所有文件类型
        public async Task<List<TypesModel>> GetFileTypesAsync()
        {
            try
            {
                Console.WriteLine("正在调用API: file/types, BaseUrl: " + _httpClient.BaseAddress);

                // 先检查服务器是否可访问
                var pingResponse = await _httpClient.GetAsync("file/types", HttpCompletionOption.ResponseHeadersRead);
                if (!pingResponse.IsSuccessStatusCode)
                {
                    Console.WriteLine($"API调用失败: StatusCode={pingResponse.StatusCode}, Reason={pingResponse.ReasonPhrase}");
                    return new List<TypesModel>();
                }

                // 读取响应内容
                var responseContent = await pingResponse.Content.ReadAsStringAsync();
                Console.WriteLine("API响应内容: " + responseContent);

                // 使用更严格的反序列化选项
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true, // 忽略属性名大小写
                    ReadCommentHandling = JsonCommentHandling.Skip,
                    AllowTrailingCommas = true,
                    DefaultIgnoreCondition = JsonIgnoreCondition.Never,
                    IncludeFields = true
                };

                // 反序列化响应
                var response = JsonSerializer.Deserialize<List<FileTypeResponse>>(responseContent, options);

                // 添加详细调试日志
                if (response != null)
                {
                    Console.WriteLine("成功获取到文件类型数量: " + response.Count);

                    // 打印每个文件类型的详细信息
                    for (int i = 0; i < response.Count; i++)
                    {
                        var type = response[i];
                        Console.WriteLine($"文件类型 {i + 1}: Id={type.Id}, TypeName={type.TypeName}, MemoryStrength={type.MemoryStrength}");
                    }

                    // 转换为TypesModel
                    var result = response.Select(type => new TypesModel
                    {
                        FileTypeID = Convert.ToInt32(type.Id),
                        FileTypeName = type.TypeName,
                        MemoryStrength = type.MemoryStrength
                    }).ToList();

                    // 打印转换后的结果
                    Console.WriteLine("转换后的TypesModel数量: " + result.Count);
                    for (int i = 0; i < result.Count; i++)
                    {
                        var model = result[i];
                        Console.WriteLine($"转换后的模型 {i + 1}: FileTypeID={model.FileTypeID}, FileTypeName={model.FileTypeName}, MemoryStrength={model.MemoryStrength}");
                    }

                    return result;
                }
                Console.WriteLine("API返回了空响应");
                return new List<TypesModel>();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取文件类型时发生异常: {ex.Message}\n{ex.InnerException?.Message}\n{ex.StackTrace}");
                // 发生错误时返回空列表或使用本地缓存
                return new List<TypesModel>();
            }
        }

        // 获取所有文件及其最后时间戳
        public async Task<List<TimeStampModel>> GetFilesAsync()
        {
            try
            {
                var response = await _httpClient.GetFromJsonAsync<List<FileWithLastTimestampResponse>>("file");
                if (response != null)
                {
                    var result = new List<TimeStampModel>();

                    foreach (var file in response)
                    {
                        var fileModel = new TimeStampModel
                        {
                            FileID = Convert.ToInt32(file.Id),
                            FilePath = file.SavedPath,
                            FileName = file.FileName,
                            TypeName = file.FileTypeName,
                            TypeID = Convert.ToInt32(file.FileTypeId)
                        };

                        if (file.LastTimestamp != null)
                        {
                            fileModel.Time = file.LastTimestamp.Time;
                            fileModel.OpenTime = file.LastTimestamp.OpenTime;
                        }

                        result.Add(fileModel);
                    }

                    return result;
                }
                return new List<TimeStampModel>();
            }
            catch
            {
                // 发生错误时返回空列表
                return new List<TimeStampModel>();
            }
        }

        // 添加新文件
        public async Task<bool> AddFileAsync(TimeStampModel fileInfo)
        {
            try
            {
                var request = new AddFileRequest
                {
                    FileName = fileInfo.FileName,
                    SavedPath = fileInfo.FilePath,
                    FileTypeId = fileInfo.TypeID
                };

                var response = await _httpClient.PostAsJsonAsync("file", request);
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        // 添加新的时间戳
        public async Task<bool> AddTimestampAsync(TimeStampModel timeStampModel)
        {
            try
            {
                var request = new AddTimestampRequest
                {
                    Time = timeStampModel.Time,
                    OpenTime = timeStampModel.OpenTime
                };

                var response = await _httpClient.PostAsJsonAsync($"file/{timeStampModel.FileID}/timestamps", request);
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        // 获取复习信息
        public async Task<ReviewInfoResponse?> GetReviewInfoAsync(long fileId)
        {
            try
            {
                return await _httpClient.GetFromJsonAsync<ReviewInfoResponse>($"file/{fileId}/review-info");
            }
            catch
            {
                return null;
            }
        }

        // 添加文件类型
        public async Task<bool> AddFileTypeAsync(TypesModel typeModel)
        {
            try
            {
                var request = new AddFileTypeRequest
                {
                    TypeName = typeModel.FileTypeName,
                    MemoryStrength = typeModel.MemoryStrength
                };

                var response = await _httpClient.PostAsJsonAsync("file/types", request);
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        // 删除文件类型
        public async Task<bool> DeleteFileTypeAsync(int fileTypeId)
        {
            try
            {
                var response = await _httpClient.DeleteAsync($"file/types/{fileTypeId}");
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        // 更新文件类型
        public async Task<bool> UpdateFileTypeAsync(TypesModel typeModel)
        {
            try
            {
                var request = new { TypeName = typeModel.FileTypeName, MemoryStrength = typeModel.MemoryStrength };
                var response = await _httpClient.PutAsJsonAsync($"file/types/{typeModel.FileTypeID}", request);
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        // 删除文件
        public async Task<bool> DeleteFileAsync(int fileId)
        {
            try
            {
                var response = await _httpClient.DeleteAsync($"file/{fileId}");
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
    }

    // 响应和请求模型类
    public class LoginResponse
    {
        public bool Success { get; set; }
        public string Message { get; set; } = string.Empty;
        public string? Token { get; set; }
        public UserDto? User { get; set; }
    }

    public class UserDto
    {
        public string Username { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string Role { get; set; } = string.Empty;
        public bool IsAuthenticated { get; set; }
    }

    public class LoginResult
    {
        public bool Success { get; set; }
        public string ErrorMessage { get; set; } = string.Empty;
        public UserDto? User { get; set; }
    }

    public class FileTypeResponse
    {
        public long Id { get; set; }
        public string TypeName { get; set; } = string.Empty;
        public double MemoryStrength { get; set; }
    }

    public class TimestampResponse
    {
        public DateTime Time { get; set; }
        public DateTime OpenTime { get; set; }
    }

    public class FileWithLastTimestampResponse
    {
        public long Id { get; set; }
        public string FileName { get; set; } = string.Empty;
        public string SavedPath { get; set; } = string.Empty;
        public long FileTypeId { get; set; }
        public string FileTypeName { get; set; } = string.Empty;
        public TimestampResponse? LastTimestamp { get; set; }
    }

    public class AddFileRequest
    {
        public string FileName { get; set; } = string.Empty;
        public string SavedPath { get; set; } = string.Empty;
        public long FileTypeId { get; set; }
    }

    public class AddTimestampRequest
    {
        public DateTime? Time { get; set; }
        public DateTime? OpenTime { get; set; }
    }

    public class ReviewInfoResponse
    {
        public long FileId { get; set; }
        public string FileName { get; set; } = string.Empty;
        public DateTime LastReviewTime { get; set; }
        public int ReviewCount { get; set; }
        public double MemoryStrength { get; set; }
        public DateTime NextReviewTime { get; set; }
        public bool IsDueForReview { get; set; }
    }

    public class AddFileTypeRequest
    {
        public string TypeName { get; set; } = string.Empty;
        public double MemoryStrength { get; set; }
    }
}